<template>
    <div class="payment-result">
        <van-nav-bar title="支付结果" left-arrow @click-left="onBack" />

        <div class="result-container" v-if="dataInfo">
            <div class="status-icon" :class="{ 'success-icon': success, 'fail-icon': !success }">
                <i class="van-icon" :class="{ 'van-icon-success': success, 'van-icon-cross': !success }"></i>
            </div>

            <div class="status-text">
                <h3>{{ success ? '支付成功' : '支付失败' }}</h3>
                <p v-if="success">订单号: {{ dataInfo.order_number }}</p>
                <p v-if="success">支付金额: {{ dataInfo.amount }}元</p>
                <p v-if="success">支付时间: {{ payTime }}</p>
                <p v-else>失败原因: {{ getReasonText() }}</p>
            </div>

            <div class="action-buttons">
                <van-button type="primary" @click="goToOrderDetail" v-if="success">查看订单</van-button>
                <van-button type="default" @click="retryPayment" v-else>重新支付</van-button>
                <van-button type="default" @click="goHome" style="margin-top: 15px;">返回首页</van-button>
            </div>
        </div>

        <div v-else class="loading-container">
            <van-loading type="spinner" size="30px" text="加载中..." />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { showToast } from 'vant';
import { useOrderStore, useProductStore } from '@/store/counter';
import api from '@/api/history.js';
import { recordPurchase } from '@/api/history'


const orderId = ref(null);
const userId = ref(null);
const productId = ref(null);
const route = useRoute();
const router = useRouter();
const orderStore = useOrderStore();
const productStore = useProductStore();

productId.value = productStore.productId;

// 状态
const dataInfo = ref(null);
const success = ref(false);
const payTime = ref('');
const reason = ref('');




onMounted(async () => {
    console.log(route.query);
    // http://s37ba8f8.natappfree.cc/payment/sandbox_result?charset=utf-8&out_trade_no=ORDER7356490126064750592&method=alipay.trade.page.pay.return&total_amount=0.01&sign=OkTYEqSd2ERi1KqDkYJ37%2F1q2AYYKQ8UFtYqFGW0fQIk2ws7rar5vp6vOYJTN4d8wst%2Fj6dEA4pJd1FoHFYIpgRVApeZ%2BzRSEodsNjxhtL9vP6Ofam1iU%2Fk5u5is0HzOcfo9PhosHWa1d4%2F4xoWU1hos8%2FGJvgygYiDdXQp%2F2IkgnaA2ZXWpvrZmXqtK9HdREaOX7MwulpXIMoch3JHk2kGEbNNgCzCGamG4WojuDD79XU0QHXpjzTjPvGhgfHFEaRbMYQmmGADrM4qRZOlfDk3H6N%2BQF%2FzCCcBegeMatIcrtRIA7iL8H3RK3op0JNObhmQSUsKrFLyYU2D4WwAQqQ%3D%3D&trade_no=2025073122001401120506119214&auth_app_id=9021000150667921&version=1.0&app_id=9021000150667921&sign_type=RSA2&seller_id=2088721074001114&timestamp=2025-07-31+10%3A54%3A47
    const out_trade_no = route.query.out_trade_no;
    console.log('============订单编号=========', out_trade_no);
    orderId.value = orderStore.orderId;
    console.log('订单ID!!!!：', orderId.value);


    // if (!orderId.value) {
    //     showToast('缺少订单信息');
    //     // router.push('/');
    //     return;
    // }


    try {
        // 获取支付状态
        const res = await api.post(`/payment/payment_status/${out_trade_no}`);
        console.log(res);
        console.log('获取支付结果:', res.data.data);
        dataInfo.value = res.data.data;
        userId.value = res.data.data.user_id;

        console.log('====获取支付结果:', dataInfo.value);
        if (res.payment_status === 'paid') {
            // 支付成功：调用recordPurchase记录购买行为
            if (userId.value && productId.value && orderId.value) {
                await recordPurchase(userId.value, productId.value, orderId.value)
                showToast('购买记录已保存')
            } else {
                console.warn('缺少参数，无法记录购买行为')
                showToast('购买记录保存失败：参数缺失')
            }
        }


        const paid_at = dataInfo.value.paid_at;

        const formatted = dayjs(paid_at).format('YYYY-MM-DD HH:mm:ss');
        // 判断支付状态
        success.value = dataInfo.value.order_status === "paid";
        payTime.value = formatted || '';

        console.log('获取订单详情: success.value =', success.value);
        console.log('获取订单详情: payTime.value =', payTime.value);

        if (!success.value) {
            // 设置失败原因
            if (orderInfo.value.payment_status === "cancelled") {
                reason.value = '用户取消支付';
            } else if (orderInfo.value.payment_status === "timeout") {
                reason.value = '支付超时';
            } else {
                reason.value = '支付失败';
            }
        }
    } catch (error) {
        showToast('获取支付结果失败');
        console.error('获取订单详情失败:', error);
    }
});

// 获取失败原因文本
const getReasonText = () => {
    return reason.value || '支付失败，请重试';
};

// 导航方法
const goToOrderDetail = () => {
    router.push(`/order/detail/${orderId.value}`);
};

// 重新支付
const retryPayment = () => {
    router.push(`/order/detail/${orderId.value}`);
};

const goHome = () => {
    router.push('/');
};

const onBack = () => {
    router.back();
};
</script>

<style scoped>
.payment-result {
    min-height: 100vh;
    background-color: #f7f8fa;
}

.result-container {
    padding: 40px 20px;
    text-align: center;
}

.status-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin: 0 auto 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.success-icon {
    background-color: #07c160;
    color: white;
}

.fail-icon {
    background-color: #ee0a24;
    color: white;
}

.status-text {
    margin: 40px 30px;
    text-align: center;
}

.status-text h3 {
    font-size: 20px;
    margin-bottom: 10px;
}

.status-text p {
    color: #666;
    margin-bottom: 5px;
}

.action-buttons {
    padding: 0 20px;
}

.loading-container {
    padding-top: 100px;
    text-align: center;
}
</style>